package com.stone.framework.batch.reader;

import java.util.ArrayList;
import java.util.List;

import org.springframework.batch.item.adapter.ItemReaderAdapter;
import org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader;
import org.springframework.util.ClassUtils;

public class ItemStreamReaderAdapter<T> extends AbstractItemCountingItemStreamItemReader<T> {

    private ItemReaderAdapter<List<T>> itemReaderAdapter = new ItemReaderAdapter<>();

    private List<T> items = new ArrayList<>();

    public ItemStreamReaderAdapter() {
        setName(ClassUtils.getShortName(ItemStreamReaderAdapter.class));
    }

    @Override
    protected T doRead() throws Exception {
        if (!items.isEmpty()) {
            return items.remove(0);
        }
        return null;
    }

    @Override
    protected void doOpen() throws Exception {
        items = this.itemReaderAdapter.read();
    }

    @Override
    protected void doClose() throws Exception {
        items = null;
    }

    public void setTargetObject(Object targetObject) {
        this.itemReaderAdapter.setTargetObject(targetObject);
    }

    public void setTargetMethod(String targetMethod) {
        this.itemReaderAdapter.setTargetMethod(targetMethod);
    }

    public void setArguments(Object[] arguments) {
        this.itemReaderAdapter.setArguments(arguments);
    }

}
